package cn.imvc.app.models;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import cn.imvc.app.domains.GoodsState;
import cn.imvc.app.entities.GoodsPrice;
import cn.imvc.app.entities.GoodsSku;
import cn.imvc.app.entities.Member;
import cn.imvc.app.repositories.GoodsPriceRepository;
import cn.imvc.app.repositories.GoodsSkuRepository;

@Service
public class GoodsPriceModelImpl implements GoodsPriceModel {
	@Autowired
	private GoodsPriceRepository goodsPriceRepository;
	@Autowired
	private GoodsSkuRepository goodsSkuRepository;
	@Value("${goods.defaultPriceClassCode}")
	private String defaultPriceClassCode;

	@Override
	public Map<String,Object> getGoodsPricesByMemberIdAndGoodsSkuId(Integer skuId, Member member) {
		Map<String,Object> resultMap= new HashMap<>();
		List<GoodsPrice> result = null;
		GoodsPrice compareGoodsPrice =null;
		GoodsSku goodsSku = goodsSkuRepository.getOne(skuId);
		resultMap.put("goodsSkuState", goodsSku.getState());
		if(goodsSku.getState() == (byte)GoodsState.GIFT_STATE.getCode()){//如果是赠品，显示积分
			compareGoodsPrice = goodsPriceRepository.findPriceBySkuIdAndPriceCode(skuId, defaultPriceClassCode);
			resultMap.put("needPoints", goodsSku.getPoints());
			resultMap.put("goodsPrice", compareGoodsPrice);
			return  resultMap;
		}
		if (member != null) {
			compareGoodsPrice = goodsPriceRepository.findPriceBySkuIdAndMemderId(skuId, member.getId());
		}else{
			compareGoodsPrice = goodsPriceRepository.findPriceBySkuIdAndPriceCode(skuId, defaultPriceClassCode);
		}
		if (compareGoodsPrice != null) {
			Integer comparePrice = compareGoodsPrice.getPrice();
			List<GoodsPrice> allPricesOfSku = goodsPriceRepository.findByGoodsSkuId(skuId);
			result = allPricesOfSku.stream().filter((price) -> {
				if (price.getPrice() == null) {
					return false;
				}
				return price.getPrice() >= comparePrice;
			}).collect(Collectors.toList());
			result.sort((a, b) ->  b.getPrice() - a.getPrice());
			resultMap.put("goodsPriceList", result);
			return resultMap;
		}
		return resultMap;
	}

	public GoodsPrice getMemberGoodsPrices(Integer skuId, Member member) {
		GoodsPrice gp = null;
		if (member == null || member.getDealer() == null) {
			gp = goodsPriceRepository.findPriceBySkuIdAndPriceCode(skuId, defaultPriceClassCode);
		} else {
			gp = goodsPriceRepository.findPriceBySkuIdAndMemderId(skuId, member.getId());
		}
		if (gp == null) {
			gp = goodsPriceRepository.findPriceBySkuIdAndPriceCode(skuId, defaultPriceClassCode);
		}
		return Objects.requireNonNull(gp, "goodsPrice can't be null");
	}
}
